﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using SgmlReaderDll;

namespace mVu
{
  internal class Tube8 : Site
  {
    public override Dictionary<string, string> GetCategories()
    {
      var categories = new Dictionary<string, string>
                         {
                           {String.Empty, "http://www.tube8.com/latest"},
                           {"Amateur", "http://www.tube8.com/cat/amateur/6"},
                           {"Anal", "http://www.tube8.com/cat/anal/13"},
                           {"Asian", "http://www.tube8.com/cat/asian/12"},
                           {"Blowjob", "http://www.tube8.com/cat/blowjob/7"},
                           {"Ebony", "http://www.tube8.com/cat/ebony/4"},
                           {"Erotic", "http://www.tube8.com/cat/erotic/11"},
                           {"Fetish", "http://www.tube8.com/cat/fetish/5"},
                           {"Gay", "http://www.tube8.com/cat/gay/9"},
                           {"Hardcore", "http://www.tube8.com/cat/hardcore/1"},
                           {"Latina", "http://www.tube8.com/cat/latina/14"},
                           {"Lesbian", "http://www.tube8.com/cat/lesbian/8"},
                           {"Mature", "http://www.tube8.com/cat/mature/2"},
                           {"Shemale", "http://www.tube8.com/cat/shemale/15"},
                           {"Strip", "http://www.tube8.com/cat/strip/10"},
                           {"Teen", "http://www.tube8.com/cat/teen/3"}
                         };

      //string result = GetPageSource("http://www.tube8.com/cat");

      //if (!String.IsNullOrEmpty(result))
      //{
      //  SgmlReaderDll.SGMLReaderHelper rh = new SgmlReaderDll.SGMLReaderHelper();
      //  string xhtml = rh.ProcessString(result);
      //  XmlDocument doc = new XmlDocument();
      //  doc.LoadXml(xhtml);

      //  XmlNode ul = doc.SelectSingleNode("//ul[@class='categories-menu']");
      //  XmlNodeList nodeList = ul.SelectNodes("li");

      //  foreach (XmlNode node in nodeList)
      //  {
      //    XmlNode a = node.SelectSingleNode("a");

      //    if (a != null)
      //    {
      //      if (!categories.ContainsKey(a.InnerText))
      //      {
      //        categories.Add(a.InnerText, a.Attributes["href"].Value);
      //      }
      //    }
      //  }
      //}

      return categories;
    }

    public override Dictionary<string, string> GetSorts()
    {
      var sorts = new Dictionary<string, string>
                    {
                      {String.Empty, String.Empty},
                      {"Newest", String.Empty},
                      {"Views", "orderby=mv"},
                      {"Ratings", "orderby=tr"},
                      {"Favorites", "orderby=mf"},
                      {"Comments", "orderby=md"},
                      {"Votes", "orderby=mt"},
                      {"Longest", "orderby=ln"}
                    };

      return sorts;
    }

    public override Dictionary<string, string> GetMediaTypes()
    {
      var types = new Dictionary<string, string>
                    {
                      {"FLV", "FLV"},
                      {"3GP", "3GP"}
                    };
      return types;
    }

    public override List<Thumbnail> GetThumbnails(string baseAddress, string sort, string query, int page)
    {
      var list = new List<Thumbnail>();

      if (String.IsNullOrEmpty(baseAddress))
      {
        baseAddress = "http://www.tube8.com/latest";
      }

      var address = String.Format("{0}/page/{1}", baseAddress, page);
      address = address + (!String.IsNullOrEmpty(query) ? String.Format("/search.html?q={0}", query) : String.Empty);
      address = address +
                (!String.IsNullOrEmpty(sort)
                   ? (!String.IsNullOrEmpty(query) ? String.Format("&{0}", sort) : String.Format("?{0}", sort))
                   : String.Empty);
      var result = GetPageSource(address);

      if (!String.IsNullOrEmpty(result))
      {
        var rh = new SGMLReaderHelper();
        var xhtml = rh.ProcessString(result);

        var doc = XDocument.Parse(xhtml);

        list.AddRange(from node in doc.Descendants("div")
                      where node.Attribute("id") != null && node.Attribute("id").Value.StartsWith("video_")
                      select new Thumbnail
                               {
                                 Image = node.Descendants("img").First().Attribute("src").Value,
                                 Url = node.Descendants("a").First().Attribute("href").Value, 
                                 Title = node.Descendants().Attributes("title").First().Value, 
                                 Length = String.Format("({0})", node.Descendants("strong").First().Value)
                               });
      }

      return list;
    }

    public override Dictionary<string, string> GetVideoPaths(string url)
    {
      var dictionary = new Dictionary<string, string>();

      if (!String.IsNullOrEmpty(url))
      {
        var result = GetPageSource(url);

        if (!String.IsNullOrEmpty(result))
        {
          // Find .flv link
          var start = result.IndexOf("http://media");
          var end = result.IndexOf(".flv", start + 1) + 4;

          if (start > -1 && end > -1)
          {
            dictionary.Add("FLV", result.Substring(start, end - start));
          }

          // Find .3gp link
          start = result.IndexOf(".3gp");

          if (start > -1)
          {
            start = result.Substring(0, start).LastIndexOf("http://");
            end = result.IndexOf("\"", start + 1);

            if (start > -1 && end > -1)
            {
              dictionary.Add("3GP", result.Substring(start, end - start));
            }
          }
        }
      }

      return dictionary;
    }
  }
}